package com.itheima.service.impl;


import com.itheima.common.AuthThreadLocal;
import com.itheima.common.CustomException;
import com.itheima.utils.SnowflakeUtils;
import com.itheima.dto.DishDto;
import com.itheima.dto.DishFlavorDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.DishFlavorMapper;
import com.itheima.mapper.DishMapper;
import com.itheima.service.DishService;
import com.itheima.vo.DishVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author HeiMa-sw
 * @Description 菜品业务层实现类//TODO 17210
 * @Date 8:48 2022/6/8
 **/
@Service
@EnableCaching
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SnowflakeUtils snowflakeUtils;


    @Override
    public DishVo getPage(Integer page, Integer pageSize, String name) {

        DishVo dishVo = new DishVo();
        dishVo.setCurrent(page);
        if (page == 1) {
            page = 0;
        } else {
            page = (page - 1) * pageSize;
        }

        List<Dish> dishList = dishMapper.selectPage(page, pageSize, name);
        List<DishDto> dishDtoList = dishList.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            Category category = categoryMapper.selectById(dish.getCategoryId());
            dishDto.setCategoryName(category.getName());
            dishDto.setType(category.getType());
            if (dishDto.getType() == 1) {
                return dishDto;
            }else{
                return null;
            }
        }).collect(Collectors.toList());

        dishVo.setRecords(dishDtoList);
        dishVo.setSize(pageSize);
        dishVo.setTotal(dishMapper.selectcount());
        return dishVo;
    }

    @Override
    public void saveOne(final DishFlavorDto dishFlavorDto) {
        //新增到菜品表
        String empId = AuthThreadLocal.getAuth();
        Dish dish = new Dish();
        getDish(dishFlavorDto, empId, dish);
        Dish one = dishMapper.selectByIdOrName(dish.getName());
        if (one == null) {
            dishMapper.insertOne(dish);
        } else {
            throw new CustomException("菜品名字已存在,请勿重复添加");
        }
        //新增到口味表
        List<DishFlavor> flavors = dishFlavorDto.getFlavors();
        flavors = getDishFlavors(empId, dish, flavors);
        dishFlavorMapper.batchInsert(flavors);
    }

    @Override
    public void modifyOne(final DishFlavorDto dishFlavorDto) {
        String empId = AuthThreadLocal.getAuth();
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishFlavorDto, dish, "flavors");
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(empId);
        dishMapper.updateOne(dish);
        String[] dishIds = {dish.getId()};
        List<DishFlavor> flavors = dishFlavorDto.getFlavors();
        dishFlavorMapper.batchDeleteByDishIds(dishIds);
        flavors = getDishFlavors(empId, dish, flavors);
        dishFlavorMapper.batchInsert(flavors);
    }

    @Override
    public void modifyStatus(final Integer status, final String[] ids) {
        String empId = AuthThreadLocal.getAuth();
        List<Dish> dishList = dishMapper.getByIds(ids);
        dishList = dishList.stream().map(dish -> {
            if (status.equals(1)) {
                dish.setStatus(1);
            } else {
                dish.setStatus(0);
            }
            dish.setUpdateUser(empId);
            dish.setUpdateTime(LocalDateTime.now());
            return dish;
        }).collect(Collectors.toList());
        dishMapper.updateStatus(dishList);
    }

    @Override
    public List<Dish> getList(final String categoryId, final String name) {
        return dishMapper.selectList(categoryId, name);
    }

    @Override
    public Dish getById(final String id) {
        return dishMapper.selectByIdOrName(id);
    }

    @Override
    public void batchRemove(final String[] ids) {
        dishMapper.deleteByIds(ids);
    }

    /**
     * 处理菜品口味集合
     *
     * @param empId   用户id
     * @param dish    菜品
     * @param flavors 口味
     * @return 菜品口味集合
     */
    private List<DishFlavor> getDishFlavors(final String empId, final Dish dish, List<DishFlavor> flavors) {
        flavors = flavors.stream().map(a -> {
            DishFlavor dishFlavor = new DishFlavor();
            BeanUtils.copyProperties(a, dishFlavor);
            dishFlavor.setId(String.valueOf(snowflakeUtils.snowflakeId()));
            dishFlavor.setDishId(dish.getId());
            dishFlavor.setCreateTime(LocalDateTime.now());
            dishFlavor.setUpdateTime(LocalDateTime.now());
            dishFlavor.setCreateUser(empId);
            dishFlavor.setUpdateUser(empId);
            dishFlavor.setIsDeleted(0);
            return dishFlavor;
        }).collect(Collectors.toList());
        return flavors;
    }

    /**
     * 处理菜品信息
     *
     * @param dishFlavorDto 菜品口味数据对象
     * @param empId         员工id
     * @param dish          菜品
     */
    private void getDish(final DishFlavorDto dishFlavorDto, final String empId, final Dish dish) {
        BeanUtils.copyProperties(dishFlavorDto, dish, "flavors");
        dish.setId(String.valueOf(snowflakeUtils.snowflakeId()));
        dish.setStatus(1);
        dish.setSort(dishMapper.selectcount() + 1);
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setCreateUser(empId);
        dish.setUpdateUser(empId);
        dish.setIsDeleted(0);
    }

    @Override
    @CachePut(value = "dish",key = "#result")
    public List<DishFlavorDto> getDishList(final String categoryId, final Integer status) {
        String key = "dish_" + categoryId + "_" + status;
        List<DishFlavorDto> dishDtoList = null;
    /*    dishDtoList = (List<DishFlavorDto>) redisTemplate.opsForValue().get(key);*/
        if (dishDtoList != null) {
            return dishDtoList;
        } else {
            // 菜品集合
            List<Dish> dishList = dishMapper.selectList(categoryId, null);
            if (dishList != null) {
                // 分类对象
                Category category = categoryMapper.selectById(categoryId);
                dishDtoList = dishList.stream().map(dish -> {
                    if (dish.getStatus().equals(status)) {
                        DishFlavorDto dishFlavorDto = new DishFlavorDto();
                        // 获取菜品口味集合
                        List<DishFlavor> dishFlavorList = dishFlavorMapper.selectByDishId(dish.getId());
                        // 将菜品口味和菜品信息整合到数据对象中
                        BeanUtils.copyProperties(dish, dishFlavorDto);
                        dishFlavorDto.setFlavors(dishFlavorList);
                        dishFlavorDto.setType(category.getType());
                        return dishFlavorDto;
                    }
                    return null;
                }).collect(Collectors.toList());
       /*         redisTemplate.opsForValue().set(key,dishDtoList);*/
                return dishDtoList;
            } else {
                return null;
            }
        }
    }
}
